/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.core;

import java.util.LinkedList;

import org.apache.log4j.Logger;

/**
 * @author Christophe Dupriez
 *
 */
public class ReferringApplicationList extends LinkedList<ReferringApplication> {

	public static final long serialVersionUID = 1;

	/** log4j category */
	   private static Logger log = Logger.getLogger(ReferringApplicationList.class);

	public synchronized ReferringApplication getReferringApplication(String application) {
		if (this.size() <= 0) return null;
		if (application == null || application.isEmpty()) {
			//return this.getFirst();
			return null;
		}
		else {
			for (ReferringApplication x : this) {
				if (x.getApplication().equals(application)) {
					log.debug(x.toString()+", total="+x.getTotal());
					return x;
				}
			}
			return null;
		}
	}

	/* Set the entry for a given application (fields with unique values for an application) */
	public synchronized boolean setReferringApplication(ReferringApplication applicationCounts) {
		if (applicationCounts == null) return false;
		boolean modified = false;
		String applicat = applicationCounts.getApplication();
		ReferringApplication anEntry = this.getReferringApplication(applicat);
		if (anEntry == null ) {
			anEntry = new ReferringApplication(applicat);
			this.add(anEntry);
			modified = true;
		}
		modified = anEntry.putCount(applicationCounts.getCount()) | modified;
		/**Debugging code...
		int biblSize= -2 ;
		ReferringApplication aBibl = this.getReferringApplication("bibl");
		if (aBibl != null) {
			biblSize = -1;
			if (aBibl.getCount() != null) {
				biblSize = aBibl.getCount().size();
			}
		}
		**/
		log.debug("Adding "+applicationCounts.getApplication()+", "+applicationCounts.getCount().size()+" roles, "+applicationCounts.getTotal()+" ref.: "
				+this.size()+" applications with "+anEntry.getCount().size()+" roles in "+anEntry.getApplication()/*+" Bibl="+biblSize*/);
		return modified;
	}

}
